package modbus

import (
	"fes/util"
)

const (
	//CoilStatusFunctionCode1
	CoilStatusFunctionCode1      = 1
	InputStatusFunctionCode2     = 2
	HoldingRegFunctionCode3      = 3
	InputRegFunctionCode4        = 4
	ForceWriteSingleCoil         = 5
	WriteSingleRegFunctionCode6  = 6
	ForceWriteMultiCoils         = 15
	WriteMultiRegsFunctionCode16 = 16
)
const (
	//InvalidFunctionCode 非法的功能码
	InvalidFunctionCode = 0x01
	//InvalidDataAddress 非法的数据地址
	InvalidDataAddress = 0x02
	//非法的数据值
	InvalidDataValue = 0x03
	//服务器故障
	ServerFailure = 0x04
	//确认
	Confirm = 0x05
	//服务器繁忙
	ServerBusy = 0x06
	//网关故障
	InvalidGate0 = 0x0A
	//网关故障
	InvalidGate1 = 0x0B
)
const (
	Int16ByteMode = 0
	Int32ByteMode = 1
	Int64ByteMode = 2
	FloatByteMode = 3
)

type ADU struct {
	transactionElementID uint16
	protocolID           uint16
	length               uint16
	unitID               uint8
	funcCode             uint8
	regAddress           uint16
	regQuantity          uint16
	body                 string
}

//高字节在前,isContains Quantity
func (apdu *ADU) enpack(isContainQuantity bool) ([]byte, int) {
	var buf [255]byte
	var index int16
	var offsetlen int16
	transactionElementID := util.Int16ToByte(int16(apdu.transactionElementID), false)
	protocolID := util.Int16ToByte(int16(apdu.protocolID), false)
	regAddress := util.Int16ToByte(int16(apdu.regAddress), false)
	var regQuantity []byte
	if isContainQuantity {
		regQuantity = util.Int16ToByte(int16(apdu.regQuantity), false)
	}

	buf[index] = transactionElementID[0]
	index++
	buf[index] = transactionElementID[1]
	index++
	buf[index] = protocolID[0]
	index++
	buf[index] = protocolID[1]
	index++
	offsetlen = index
	index += 2
	buf[index] = util.Int8ToByte(int8(apdu.unitID), false)
	index++
	buf[index] = util.Int8ToByte(int8(apdu.funcCode), false)
	index++
	buf[index] = regAddress[0]
	index++
	buf[index] = regAddress[1]
	index++
	if isContainQuantity {
		buf[index] = regQuantity[0]
		index++
		buf[index] = regQuantity[1]
		index++
	}
	var data []byte = []byte(apdu.body)
	copy(buf[index:], data[0:])
	index += int16(len(data))
	length := util.Int16ToByte(index-6, false)
	buf[offsetlen] = length[0]
	buf[offsetlen+1] = length[1]
	slice := buf[0:index]
	_ = data
	_ = buf
	return slice, len(slice)
}
